package com.ruoyi.fun.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.fun.dto.CartUpdateDto;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.fun.domain.EcCart;
import com.ruoyi.fun.service.IEcCartService;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * 移动端购物车Controller
 * 
 * @author ruoyi
 * @date 2025-01-15
 */
@Anonymous
@RestController
@RequestMapping("/mobile/cart")
public class EcMobileCartController extends BaseController
{
    @Autowired
    private IEcCartService ecCartService;

    /**
     * 查询用户购物车列表
     */
    @GetMapping("/list")
    public TableDataInfo list(EcCart ecCart)
    {
        System.out.println("=== 购物车列表接口被调用 ===");
        System.out.println("=== 接收到的查询参数: " + ecCart);
        
        // 从token中获取当前登录用户ID
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
            System.out.println("=== 从token获取的用户ID: " + userId);
        } catch (Exception e) {
            System.out.println("=== 获取用户ID失败: " + e.getMessage());
            // 如果无法从token获取用户ID，尝试从请求参数获取
            userId = ecCart.getUserId();
            System.out.println("=== 从请求参数获取的用户ID: " + userId);
        }
        
        if (userId == null) {
            System.out.println("=== 用户ID为空，返回空列表 ===");
            return getDataTable(new java.util.ArrayList<>());
        }
        ecCart.setUserId(userId);
        
        // 设置组织ID，优先使用前端传递的orgId，否则使用默认值103
        Long orgId = ecCart.getOrgId() != null ? ecCart.getOrgId() : getOrgId();
        ecCart.setOrgId(orgId);
        System.out.println("=== 使用的组织ID: " + orgId);
        System.out.println("=== 最终查询条件: " + ecCart);
        
        startPage();
        List<EcCart> list = ecCartService.selectEcCartList(ecCart);
        
        // 确保list不为null
        if (list == null) {
            list = new java.util.ArrayList<>();
        }
        
        return getDataTable(list);
    }

    /**
     * 获取购物车详细信息
     */
    @GetMapping(value = "/{cartId}")
    public AjaxResult getInfo(@PathVariable("cartId") String cartId)
    {
        try {
            Long longCartId = Long.parseLong(cartId);
            return success(ecCartService.selectEcCartByCartIdAndOrgId(longCartId, getOrgId()));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid cartId format: " + cartId);
        }
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody EcCart ecCart)
    {
        System.out.println("=== 购物车添加接口被调用 ===");
        System.out.println("=== 接收到的购物车数据: " + ecCart);
        
        // 从请求参数中获取用户ID，支持匿名访问
        Long userId = ecCart.getUserId();
        System.out.println("=== 用户ID: " + userId);
        
        if (userId == null) {
            System.out.println("=== 用户ID为空，返回错误 ===");
            return AjaxResult.error("用户ID不能为空");
        }
        
        ecCart.setUserId(userId);
        // 设置组织ID，优先使用前端传递的orgId，否则使用默认值103
        Long orgId = ecCart.getOrgId() != null ? ecCart.getOrgId() : getOrgId();
        ecCart.setOrgId(orgId);
        System.out.println("=== 使用的组织ID: " + orgId);
        
        System.out.println("=== 设置后的购物车数据: " + ecCart);
        
        try {
            // 检查购物车中是否已存在该商品（同时检查productId和skuId）
            EcCart existingCart = new EcCart();
            existingCart.setUserId(userId);
            existingCart.setProductId(ecCart.getProductId());
            existingCart.setSkuId(ecCart.getSkuId());
            existingCart.setOrgId(orgId);
            
            System.out.println("=== 查询已存在商品的条件: " + existingCart);
            
            List<EcCart> existingItems = ecCartService.selectEcCartList(existingCart);
            System.out.println("=== 查询到的已存在商品数量: " + (existingItems != null ? existingItems.size() : 0));
            
            if (existingItems != null && !existingItems.isEmpty()) {
                // 如果商品已存在，更新数量
                EcCart cartItem = existingItems.get(0);
                System.out.println("=== 商品已存在，原数量: " + cartItem.getQuantity() + ", 新增数量: " + ecCart.getQuantity());
                
                cartItem.setQuantity(cartItem.getQuantity() + ecCart.getQuantity());
                System.out.println("=== 更新后数量: " + cartItem.getQuantity());
                
                int result = ecCartService.updateEcCart(cartItem);
                System.out.println("=== 更新结果: " + result);
                
                if (result > 0) {
                    System.out.println("=== 更新成功，返回数据: " + cartItem);
                    return AjaxResult.success("操作成功", cartItem);
                } else {
                    System.out.println("=== 更新失败 ===");
                    return AjaxResult.error("操作失败");
                }
            } else {
                // 如果商品不存在，新增到购物车
                System.out.println("=== 商品不存在，新增到购物车 ===");
                
                int result = ecCartService.insertEcCart(ecCart);
                System.out.println("=== 新增结果: " + result);
                
                if (result > 0) {
                    System.out.println("=== 新增成功，返回数据: " + ecCart);
                    return AjaxResult.success("操作成功", ecCart);
                } else {
                    System.out.println("=== 新增失败 ===");
                    return AjaxResult.error("操作失败");
                }
            }
        } catch (Exception e) {
            System.out.println("=== 购物车添加异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("添加购物车失败: " + e.getMessage());
        }
    }

    /**
     * 修改购物车商品数量
     */
    @PutMapping("/update")
    public AjaxResult edit(@RequestBody CartUpdateDto cartUpdateDto)
    {
        // 从请求参数中获取用户ID，支持匿名访问
        Long userId = cartUpdateDto.getUserId();
        if (userId == null) {
            return AjaxResult.error("用户ID不能为空");
        }
        
        // 验证cartId是否存在
        Long cartId = cartUpdateDto.getCartIdAsLong();
        if (cartId == null) {
            return AjaxResult.error("购物车ID不能为空");
        }
        
        // 获取组织ID，优先使用前端传递的orgId，否则使用默认值
        Long orgId = cartUpdateDto.getOrgId() != null ? cartUpdateDto.getOrgId() : getOrgId();
        
        // 检查购物车记录是否存在且属于当前用户
        EcCart existingCart = ecCartService.selectEcCartByCartIdAndOrgId(cartId, orgId);
        if (existingCart == null || !existingCart.getUserId().equals(userId)) {
            return AjaxResult.error("购物车记录不存在或无权限操作");
        }
        
        // 创建EcCart对象并设置属性
        EcCart ecCart = new EcCart();
        ecCart.setCartId(cartId);
        ecCart.setUserId(userId);
        ecCart.setOrgId(orgId);
        
        if (cartUpdateDto.getQuantity() != null) {
            ecCart.setQuantity(Long.valueOf(cartUpdateDto.getQuantity()));
        }
        
        if (cartUpdateDto.getChecked() != null) {
            // 如果需要处理checked字段，可以在这里添加逻辑
        }
        
        int result = ecCartService.updateEcCart(ecCart);
        if (result > 0) {
            // 返回更新后的购物车信息
            EcCart updatedCart = ecCartService.selectEcCartByCartIdAndOrgId(cartId, orgId);
            return AjaxResult.success("操作成功", updatedCart);
        } else {
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 删除单个购物车商品
     */
    @DeleteMapping("/{cartId}")
    public AjaxResult removeSingle(@PathVariable String cartId, @org.springframework.web.bind.annotation.RequestParam Long orgId)
    {
        logger.info("========== 开始删除单个购物车商品 ===========");
        logger.info("请求参数 cartId: {}", cartId);
        logger.info("请求参数 orgId: {}", orgId);
        logger.info("请求时间: {}", new Date());
        
        try {
            // 获取当前用户信息
            Long userId = null;
            try {
                userId = SecurityUtils.getUserId();
                logger.info("当前用户ID: {}", userId);
            } catch (Exception e) {
                logger.error("获取用户ID异常: {}", e.getMessage(), e);
            }
            
            // 将字符串转换为Long，避免大数值精度丢失
            Long longCartId;
            try {
                longCartId = Long.parseLong(cartId);
            } catch (NumberFormatException e) {
                logger.error("购物车ID格式错误: {}", cartId);
                throw new IllegalArgumentException("Invalid cartId format: " + cartId);
            }
            logger.info("转换后的购物车ID: {}", longCartId);
            
            logger.info("调用删除服务方法...");
            int result = ecCartService.deleteEcCartByCartIds(new Long[]{longCartId}, orgId);
            logger.info("删除服务返回结果: {}", result);
            
            AjaxResult ajaxResult = toAjax(result);
            logger.info("最终返回结果: {}", ajaxResult);
            logger.info("========== 删除单个购物车商品成功结束 ===========");
            
            return ajaxResult;
        } catch (Exception e) {
            logger.error("删除单个购物车商品异常: {} - {}", e.getClass().getSimpleName(), e.getMessage());
            logger.error("异常堆栈信息:", e);
            
            AjaxResult errorResult = error("删除购物车商品失败：" + e.getMessage());
            logger.error("返回错误响应: {}", errorResult);
            logger.error("========== 删除单个购物车商品异常结束 ===========");
            
            return errorResult;
        }
    }

    /**
     * 批量删除购物车商品请求体
     */
    public static class BatchDeleteRequest {
        private String[] cartIds;
        private Long orgId;
        
        public String[] getCartIds() { return cartIds; }
        public void setCartIds(String[] cartIds) { this.cartIds = cartIds; }
        public Long getOrgId() { return orgId; }
        public void setOrgId(Long orgId) { this.orgId = orgId; }
    }
    
    /**
     * 批量删除购物车商品
     */
    @DeleteMapping("/batch-delete")
    public AjaxResult remove(@RequestBody BatchDeleteRequest request)
    {
        logger.info("========== 开始删除购物车商品 ==========");
        logger.info("请求参数 cartIds: {}", Arrays.toString(request.getCartIds()));
        logger.info("请求参数 orgId: {}", request.getOrgId());
        logger.info("请求时间: {}", new Date());
        
        try {
            String[] cartIds = request.getCartIds();
            Long orgId = request.getOrgId();
            
            // 获取当前用户信息
            Long userId = null;
            try {
                userId = SecurityUtils.getUserId();
                logger.info("当前用户ID: {}", userId);
            } catch (Exception e) {
                logger.error("获取用户ID异常: {}", e.getMessage(), e);
            }
            
            // 将字符串数组转换为Long数组，避免大数值精度丢失
            Long[] longCartIds = new Long[cartIds.length];
            for (int i = 0; i < cartIds.length; i++) {
                try {
                    longCartIds[i] = Long.parseLong(cartIds[i]);
                } catch (NumberFormatException e) {
                    logger.error("购物车ID格式错误: {}", cartIds[i]);
                    throw new IllegalArgumentException("Invalid cartId format: " + cartIds[i]);
                }
            }
            logger.info("转换后的购物车ID数组: {}", Arrays.toString(longCartIds));
            
            logger.info("调用删除服务方法...");
            int result = ecCartService.deleteEcCartByCartIds(longCartIds, orgId);
            logger.info("删除服务返回结果: {}", result);
            
            AjaxResult ajaxResult = toAjax(result);
            logger.info("最终返回结果: {}", ajaxResult);
            logger.info("========== 删除购物车商品成功结束 ==========");
            
            return ajaxResult;
        } catch (Exception e) {
            logger.error("删除购物车商品异常: {} - {}", e.getClass().getSimpleName(), e.getMessage());
            logger.error("异常堆栈信息:", e);
            
            AjaxResult errorResult = error("删除购物车商品失败：" + e.getMessage());
            logger.error("返回错误响应: {}", errorResult);
            logger.error("========== 删除购物车商品异常结束 ==========");
            
            return errorResult;
        }
    }
    
    /**
     * 清空用户购物车
     */
    @DeleteMapping("/clear")
    public AjaxResult clear(@RequestBody EcCart requestCart)
    {
        // 从请求参数中获取用户ID，支持匿名访问
        Long userId = requestCart.getUserId();
        if (userId == null) {
            return AjaxResult.error("用户ID不能为空");
        }
        
        // 查询用户所有购物车商品
        EcCart ecCart = new EcCart();
        ecCart.setUserId(userId);
        ecCart.setOrgId(getOrgId());
        List<EcCart> cartItems = ecCartService.selectEcCartList(ecCart);
        
        if (cartItems != null && !cartItems.isEmpty()) {
            Long[] cartIds = cartItems.stream().map(EcCart::getCartId).toArray(Long[]::new);
            return toAjax(ecCartService.deleteEcCartByCartIds(cartIds));
        }
        
        return success();
    }
    /**
     * 根据cartId和组织ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:ecmobilecart:query')")
    @GetMapping(value = "/{cartId}/org/{orgId}")
    public AjaxResult getInfoByOrgId(@PathVariable("cartId") Long cartId, @PathVariable("orgId") Long orgId)
    {
        return success(ecCartService.selectEcCartByCartIdAndOrgId(cartId, orgId));
    }

    /**
     * 根据组织ID查询列表
     */
    @PreAuthorize("@ss.hasPermi('system:ecmobilecart:list')")
    @GetMapping("/org/{orgId}")
    public TableDataInfo listByOrgId(@PathVariable Long orgId)
    {
        startPage();
        EcCart ecCart = new EcCart();
        List<EcCart> list = ecCartService.selectEcCartListByOrgId(ecCart, orgId);
        return getDataTable(list);
    }


}